# -*- coding: utf-8 -*-
# 周期性任务处理
import os
from apscheduler.schedulers.gevent import GeventScheduler
from apscheduler.jobstores.mongodb import MongoDBJobStore
from apscheduler.executors.pool import ThreadPoolExecutor
from apscheduler.schedulers.base import JobLookupError
from pymongo import MongoClient

try:
    import setting
except ImportError:
    import sys

    sys.path.append('..')
    import setting

if setting.db['username'] and setting.db['password']:
    JobsClient = MongoClient(
        'mongodb://' + setting.db['username'] + ':' + setting.db['password'] + '@' + setting.db['host'])
else:
    JobsClient = MongoClient()

WeekDay = {
    1: 'mon', 2: 'tue', 3: 'wed', 4: 'thu', 5: 'fri', 6: 'sat', 7: 'sun',
    '1': 'mon', '2': 'tue', '3': 'wed', '4': 'thu', '5': 'fri', '6': 'sat', '7': 'sun'
}

jobstores = {
    'default': MongoDBJobStore(database='w06', client=JobsClient),
}
executors = {
    'default': ThreadPoolExecutor(20)
}

scheduler = GeventScheduler(jobstores=jobstores, executors=executors)
if os.getcwd()[-3:] == 'web':
    scheduler.start()


def addScheduler(func, jobid, weekday='*', hour='*', minute='*', args=()):
    """
    添加cron任务
    param: func    <function>
    param: jobid   <str>
    param: weekday <str>
    param: hour    <str>
    param: minute  <str>
    param: args    <tuple>
    """
    scheduler.add_job(func, args=args, trigger='cron', day_of_week=weekday, hour=hour, minute=minute, id=jobid,
                      replace_existing=True)


def delScheduler(jobid):
    """
    删除cron任务
    param: jobid <str>
    """
    try:
        scheduler.remove_job(jobid)
    except JobLookupError:
        pass
